/**
 * mysql操作
 */

const mysql = require('mysql');

let mysqlTool = {};

let connection;

/**
 * 初始化连接
 * {
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: 'root',
    database: 'clear'
}
 */
mysqlTool.initConnection = function (config) {
    if (!connection) {
        connection = mysql.createConnection(config)
    }
}

/**
 * 异步查询
 * @param sql sql
 * @param callback = function (err, rows, fields) {
        if (err)
            console.error(err);
        else {
            console.log(rows);
        }
    }
 */
mysqlTool.query = function (sql, callback) {
    if (!connection) {
        throw 'mysql connection未初始化';
    }
    connection.connect();
    connection.query(sql, callback);
    //关闭连接
    connection.end();
}

module.exports = mysqlTool;
